#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os,time,json
from MsgProcess import MsgProcess, MsgType#自美系统内核
import serial #导入模块

def preservation(state="r",data={}):
    if state =="w":
        with open("plugin/RemoteControlWIFI/data.txt","w", encoding='utf-8') as f:
            f.write(json.dumps( data,ensure_ascii=False,indent=2 ))
        #重新生成config.json

        config1='''{
"name": "RemoteControlWIFI",
"triggerwords":["帮我", "学习","查看红外","删除红外"],
"IsEnable": true,
"IsSystem": false,
"AutoLoader": false,

"icon":"0",
"displayName": "万能开关红外遥控器",
"description": "触发词:帮我xx, 学习xx,查看红外,删除红外。   在本页面查看最新语音学习的指令，需要返回上一级再次进入本插件。",
"version": "0",
"updateTime":"",

"repository": {
    "type": "",
    "url": ""
}

,"control":[
 		{  "lable":"执行状态",
			"body":[
				{
					"type":"text",
					"getvalue":"0",
					"text":"发送"
				},
				{
					"type":"text",
					"getvalue":"1",
					"text":"时间"
				}

					]
		}  ,

    {
        "lable":"已经学会的红外",
        "body":'''


        config3='''}]}'''
        config2=[]

        for x in data:
            dicts = {}
            dicts["type"] =  "button"
            dicts["size"] =  "mini"
            dicts["setvalue"] =  "帮我"+x
            dicts["text"] =  "帮我"+x
            config2.append(  dicts )

        with open("plugin/RemoteControlWIFI/config.json","w", encoding='utf-8') as f:
            f.write(config1+json.dumps( config2,ensure_ascii=False,indent=2 )+config3)
            

    if state =="r":
        try:
            with open("plugin/RemoteControlWIFI/data.txt", encoding='utf-8') as f:
                return json.loads(f.read())
        except:
            return {}



class RemoteControlWIFI(MsgProcess):
    os.system("sudo chmod -R 777 plugin/RemoteControlWIFI")

    #红外数据
    data = preservation()
    temporary=""
    #执行入口
    def Text(self, message):
        txt = message['Data'] 

        #判读是否是万能开关发过来的消息类型
        if isinstance(txt, dict) and 'type' in dict(txt).keys() and  txt['type'] == 'post' :
            #+1写入数据{xxx:1}
            self.data[ self.temporary[2:] ]=int( txt["message"])
            preservation("w",self.data)
            self.say("正在学习红外指令,请按遥控器该功能按键,学习完成后蓝灯会熄灭!")

        #判读是否是万能开关发过来的消息类型
        if isinstance(txt, dict) and 'type' in dict(txt).keys() and  txt['type'] == 'get' :
                for x in self.data:
                    #命令匹配
                    if self.data[x] == int( txt["message"] ):
                        data = {'action':"","0": x,"1":time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) }                 
                        self.send(MsgType.Text, Receiver='MqttProxy', Data=data)
                        self.say("已{0}".format(x))

        #判读是否是字符消息
        if not isinstance(txt, dict):
            if txt.count("学习") :
                if  len(txt)>=3:
                    self.temporary=txt
                    #如果字符指令一样 那么机器指令不变
                    #如果字符指令没有 那么机器指令加一

                    if txt[2:] in self.data:
                        key = self.data[txt[2:]]
                    else:
                        key = len( self.data ) +1

                    self.send(MsgType=MsgType.Text,    Receiver="MqttProxy", Data={"type":"post","message": key }   )
                else:
                    self.say("学习红外指令未完成")

            if txt.count("帮我"):
                for x in self.data:
                    #命令匹配
                    if x == txt[2:]:
                        self.send(MsgType=MsgType.Text, Receiver="MqttProxy", Data={"type":"get",  "message":   self.data[x] }   )
                        return 0

                self.say("没有找到该红外指令")

            if txt.count("查看"):
                if len(self.data)==0:
                    self.say("没有学习红外指令")
                    return 0

                self.say( "目前有{0}个红外指令，你可以说帮我".format(len(self.data)) )
                for x in self.data:
                    self.say(x)
                    time.sleep(0.1)

            if txt.count("删除"):
                self.data={}
                preservation("w",self.data)
                self.say("已经删除所有红外指令")
            
